package com.chenfan.ccp.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.CollectionUtils;

import java.util.LinkedList;
import java.util.List;


/**
 * 用于处理一些必须要等待事务提交后执行的操作
 */
@Slf4j
public class TransactionLifeCycleUtils {
    private static ThreadLocal<List<Runnable>> threadLocalRunnableList = new ThreadLocal<>();

    private static TransactionSynchronization action = new TransactionSynchronization() {
        @Override
        public void afterCompletion(int status) {
            if (status == STATUS_COMMITTED) {
                List<Runnable> runnableList = threadLocalRunnableList.get();
                threadLocalRunnableList.remove();
                runnableList.forEach(Runnable::run);
            }
            TransactionSynchronization.super.afterCompletion(status);
        }
    };


    /**
     * 完成后执行操作
     * @param task
     */
    public static void afterCommitSuccessCallback(Runnable task) {
        ThreadLocal<List<Runnable>> local = threadLocalRunnableList;
        List<Runnable> runnables = local.get();
        if(!CollectionUtils.isEmpty(runnables)){
            runnables.add(task);
        }else {
            LinkedList<Runnable> list = new LinkedList<>();
            list.add(task);
            local.set(list);
            TransactionSynchronizationManager.registerSynchronization(action);
        }
    }
}
